﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Collections.Generic;

public partial class GeoRSS : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == false)
        {
            //RegisterStartupScript("start", "javascript:load()");

            TwitterUser user = new TwitterUser(Page);
            if (user.UserName != null && Request.Params["token"] == null)
            {
                string sToken = GeoRSSLibrary.EncryptUtils.Encrypt(user.UserName + " " + user.Password);
                Response.Redirect("GeoRss.aspx?token=" + sToken);
            }
            if (user.UserName == null && Request.Params["token"] != null)
            {
                string sToken = GeoRSSLibrary.EncryptUtils.Decrypt(Request.Params["token"].ToString().Replace(" ", "+"));
                string[] sCredential = sToken.Split(' ');
                user.UserName = sCredential[0];
                user.Password = sCredential[1];
            }
            if (user.UserName == null && Request.Params["token"] == null)
            {
                Response.Redirect("SignIn.aspx");
            }

            string sGeoRss = GetTimeLineGeoRSS();

            Response.CacheControl = "No-cache";
            Response.ContentType = "text/xml";

            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            Response.Write(sGeoRss);
            Response.Flush();

            Response.End();
            
        }
    }

    private string GetTimeLineGeoRSS()
    {
        TwitterUser user = new TwitterUser(Page);
        Twitter twitter = new Twitter();

        //string sXml2 = twitter.GetUserTimeline(user.UserName, user.Password, user.UserName, Twitter.OutputFormatType.XML);
        string sXmlFriends = twitter.GetFriendsTimeline(user.UserName, user.Password, Twitter.OutputFormatType.XML);

        XDocument loaded = XDocument.Parse(sXmlFriends);

        var allElements = from stat in loaded.Descendants("status")
                          select new
                          {
                              ID = stat.Element("id").Value,
                              Text = stat.Element("text").Value,
                              Name = stat.Element("user").Element("name").Value,
                              UserImage = stat.Element("user").Element("profile_image_url").Value,
                              Description = stat.Element("text").Value,
                              Created = stat.Element("created_at").Value,
                          };

        GeoRSSLibrary.GeoRSSFeedTwitter feed = new GeoRSSLibrary.GeoRSSFeedTwitter();
        DateTime dtNow = DateTime.Now;
        foreach (var stat in allElements)
        {
            GeoRSSLibrary.GeoRSSRecord record = new GeoRSSLibrary.GeoRSSRecord();
            record.Type = "point";
            record.ID = stat.ID;
            record.Image = stat.UserImage;
            record.Title = stat.Name;
            record.RecordedTime = dtNow;// Convert.ToDateTime(stat.Created);
            record.Description = stat.Description;
            record.Coordinates = GetCoordinates(stat.Description);
            
            feed.Add(record);

            dtNow = dtNow.AddSeconds(10);
        }



        return feed.ToXML();

    }

    private double[] GetCoordinates(string sDes)
    {
        double[] coor = new double[2];
        coor[0] = 0;
        coor[1] = 0;

        if (sDes.IndexOf(System.Configuration.ConfigurationManager.AppSettings["Host"].ToString() + "/l.aspx?g=") > -1)
        {
            string sCoor = sDes.Substring(sDes.IndexOf(System.Configuration.ConfigurationManager.AppSettings["Host"].ToString() + "/l.aspx?g=") + 31);

            DataClassesDataContext dd = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["GeoTwitterDataConnectionString"].ConnectionString);
            var row = dd.Links.Single(p => p.ID == Int32.Parse(sCoor));

            coor[0] = Convert.ToDouble(row.lat);
            coor[1] = Convert.ToDouble(row.lon);
        }

        return coor;
    }
}
